package com.lion.common.spring.enhancers.advices;

import com.chris.dev.base.libs.v1.http.results.ValueResult;
import com.google.gson.Gson;
import com.lion.common.spring.enhancers.helpers.ValueResultWrapHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author Chris Chan
 * Create On 2025/7/28 下午8:29
 * Use for: ValueResult统一包装
 * Explain:
 * 如果接口的返回值被定义为基本数据类型，就要用ValueResult进行包装，以便能够转换为json
 */
@Order(-200)
@RestControllerAdvice
public class ValueResultCommonWrapAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    Gson gson;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return ValueResultWrapHelper.support(returnType, converterType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 给ResponseHeader添加Content-Type
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        // 已经有包装的就不再包装
        return body instanceof ValueResult<?> ? body : ValueResult.of(body);
    }
}
